<?php
Class Api{

	public static function get_appid()
	{
		return Config::get('weixin.appid');
	}

	public static function get_appsecret()
    {
    	return Config::get('weixin.appsecret');
    }

      //url请求方法
    public static function http_curl($url,$type="get",$res='json',$arr="")
    {
    	$ch = curl_init();
    	curl_setopt($ch,CURLOPT_URL,$url);
    	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    	if($type == "post"){
    		curl_setopt($ch,CURLOPT_POST,1);
    		curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
    	}

    	$output = curl_exec($ch);
    	
    	if($res="json"){
    		if(curl_errno($ch)){
    			return curl_errno($ch);
    		}else{
    			return json_decode($output,true);  //把返回的json格式的数据类型转化成数组形式
    		}
    		
    	}
        curl_close($ch);
    }


    //获取微信全局access_token
    public static function get_access_token()
    {
      //   $appid = self::get_appid();
      //   $appsecret = self::get_appsecret();
      //   $time = time()-7000;
      //   $str = DB::table('weixinconf')->first();
      //   if($str['access_token'] && $time<$str['access_token_time']){
			   //   return $str['access_token'];
      //   }else{
      //   	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
    		// $res = self::http_curl($url,'get','json');
    	 // 	$access_token = $res['access_token'];
    	 // 	$time = time();
    	 //    $str = DB::table('weixinconf')->where('id','=',1)->update(array('access_token'=>$access_token,'access_token_time'=>$time));
      //   	return $access_token;
      //   }


      $redis = new redis();  
      $redis->connect('127.0.0.1', 6380);  
      $redis->auth('pengsu');
      $result = $redis->get('youledi_access_token');  
      var_dump($result);
      $result = unserialize($result);
      var_dump($result);
      exit;
      if($result['expire'] > time()){
        $access_token = $result['access_token'];
      }else{
        $access_token = '';
      }
      
      if(!$access_token)
      {
         $result = self::http_curl('https://api.weixin.qq.com/cgi-bin/token','grant_type=client_credential&appid=wx5cdb35abf2a601fb&secret=b63a32d1930fb91639a568c07a8c6049');
        if(isset($result['errcode'])){
          echo json_encode(array('401',$result));
          exit;
        }
        $access_token = $result['access_token'];
          // Save into the cache for 5 minutes
          $data = array(
            'access_token' => $access_token,
            'expire_time' => time()+7000
          );
          $redis->set('youledi_access_token',serialize($data));
        
      }
      // cache::flush(); 清空所有缓存
       
      $result = $redis->get('youledi_jsapi_ticket');
      $result = unserialize($result);
      $jsapi_ticket = $result['jsapi_ticket'];
      
      if($type != '0'){
        return $access_token;
      }

      if(!$jsapi_ticket)
      {
         $res = self::http_curl('https://api.weixin.qq.com/cgi-bin/ticket/getticket','access_token='.$access_token.'&type=jsapi');
        if(isset($res['errcode']) AND $res['errcode'] == 0){
          $jsapi_ticket = $res['ticket'];
        }else{
          echo json_encode(array('401',$res));
          exit;
        }
        $data = array(
          'jsapi_ticket' => $jsapi_ticket,
          'expire_time' => time()+7000
        );
          $redis->set('youledi_jsapi_ticket',$data);
        
      }
      
      
      //if( ! $signature = $this->cache->get('signature')){
        $signature = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;

        $signature = sha1($signature);
        //$this->cache->save('signature',$signature,7100);
      //}
      
      echo json_encode(array('code'=>200,'msg'=>array('signature'=>$signature,'access_token'=>$access_token,'jsapi_ticket'=>$jsapi_ticket)));
        
    }


    //获取微信网页授权的wyaccess_token
    public static function get_wyaccess_token($code)
    {

        $appid = self::get_appid();
        $appsecret = self::get_appsecret();
        $time = time()-7000;
    	$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
		$res = self::http_curl($url,'get','json');
	 	$wyaccess_token = $res['access_token'];
	 	$openid = $res['openid'];
	 	$data = array(
	 		'wyaccess_token'=>$wyaccess_token,
	 		'openid'=>$openid
	 		);
    	return $data;         
    }


    //获取调用微信jsapi的全局票据
    public static function get_jsapi_ticket()
    {
        $time = time()-7000;
        $str = DB::table('weixinconf')->where('id','=',1)->first();
    	if($str['jsapi_ticket'] && $time<$str['jsapi_ticket_time']){
            return $str['jsapi_ticket'];
        }else{
            $access_token = self::get_access_token();
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi';
            $res = self::http_curl($url);
            $jsapi_ticket = $res['ticket'];
            $time = time();
            $str = DB::table('weixinconf')->where('id','=',1)->update(array('jsapi_ticket'=>$jsapi_ticket,'jsapi_ticket_time'=>$time));
            return $jsapi_ticket;

        }


    }


    //生成随机字符串
    public static function createNonceStr($length = 16)
    {
    	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $str = "";
	    for ($i = 0; $i < $length; $i++) {
	      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	    }
	    return $str;
    }

    //获取当前网页的url
    public static function get_url()
    {

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        return $url;

    }

    //生成网页分享的参数
    public static function creat_signaturedata($url)
    {

        $jsapi_ticket = self::get_jsapi_ticket();
        $noncestr = self::createNonceStr();
        $timestamp= time();
        $appid = self::get_appid();
        //$string = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&amptimestamp=$timestamp&url=$url";
        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$noncestr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $appid,
            "nonceStr"  => $noncestr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature
        );
        return $signPackage;
        
    }


    //生成订单号
    public static function creatorder()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;


    }















































}
